<template>
  <div class="rounded w-[100%]" v-loading="loading">
    <div class="flex mb-2">
      <div class="flex-1">
        <slot name="title" :row="additionalData" />
      </div>
      <div v-if="props.isExport" class="ml-3">
        <el-button type="primary" @click="download">{{ $t('customTable.index.076547-0') }}</el-button>
      </div>
    </div>

    <slot name="tableTitle" />

    <el-table
      ref="tableRef"
      :data="listData"
      :row-key="props.selectKey"
      :border="false"
      :height="props.height"
      :max-height="props.maxHeight"
      :fit="true"
      center
      :cell-style="() => props.cellStyle"
      :header-cell-style="() => props.headerCellStyle"
      @selection-change="handleSelectionChange"
      @expand-change="expandColumn"
      :expand-row-keys="expandsKey"
      :tree-props="props.treeProps"
      class="tables my-2 w-full"
      style="height: auto;max-height: initial;"
      v-bind="props.childrenProps"
    >
      <el-table-column v-if="props.selectColumnType === 'RADIO'" align="center" :width="70" :label="$t('customTable.index.076547-1')">
        <template #default="scope">
          <el-radio
            v-if="scope.row[props.selectKey]"
            class="w-full radio flex"
            v-model="selectedData"
            :label="scope.row[props.selectKey]"
            :value="scope.row[props.selectKey]"
            @change="handleSelectionChange"
          />
        </template>
      </el-table-column>

      <el-table-column
        v-if="props.selectColumnType === 'CHECKBOX'"
        type="selection"
        align="center"
        width="50"
        fixed
        :reserve-selection="true"
        :selectable="disableIdsReturen"
      />

      <el-table-column v-if="props.expendConfig.visible" type="expand" fixed width="30">
        <template #default="{ row }">
          <div>
            <slot name="expend" :row="row" />
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="props.expendConfig.visible" label="" fixed width="60">
        <template #default="{ row }">
          <span class="cursor-pointer text-[var(--el-color-primary)]" @click="expandColumn(row, [row])"> {{ $t('customTable.index.076547-2') }} </span>
        </template>
      </el-table-column>

      <el-table-column v-if="props.showIndexColumn" type="index" :label="$t('customTable.index.076547-3')" align="center" :width="props.sequenceWidth" fixed />

      <template v-for="(propItem, index) in props.propList">
        <el-table-column
          resizable
          v-if="!propItem.visible"
          :label="propItem.label"
          :key="index"
          :header-align="propItem.headerAlign"
          :align="propItem.align"
          :width="propItem.width"
          :min-width="propItem.minWidth"
          show-overflow-tooltip
          v-bind="propItem"
        >
          <template v-if="propItem.headerSlotName" #header="column">
            <div>
              <slot :name="propItem.headerSlotName" v-bind="column"> </slot>
            </div>
          </template>
          <template #default="scope">
            <div class="w-full h-full">
              <slot
                :name="propItem.slotName"
                v-bind:row="scope.row"
                v-bind:key="scope.$index"
              >
                <div v-if="propItem.echo" class="w-full flex justify-center text-center items-center" :style="propItem.style">
                  {{ echoField(propItem.echo.options, propItem.echo.optionsValue, propItem.echo.optionsKey, scope.row[propItem.prop]) }}
                </div>
                <div class="w-full flex justify-center items-center text-center textOverflow" v-else :ref="'text-' + scope.row[props.selectKey] + '-' + index" :style="propItem.style">
                  {{ propItem.unitLeft }}{{ typeof scope.row[propItem.prop] === 'number' ? !propItem.wetherFix ? scope.row[propItem.prop].toFixed(2) : scope.row[propItem.prop] : scope.row[propItem.prop] }}{{ propItem.unitRight }}
                </div>
              </slot>
            </div>
          </template>
        </el-table-column>
      </template>

      <el-table-column v-if="props.operateFlag" :label="props.operateLabel" :width="props.operateWidth" align="center" fixed="right">
        <template #default="{ row }">
          <slot name="operate" :row="row" />
        </template>
      </el-table-column>

      <template #empty>
        <el-empty :description="$t('customTable.index.076547-4')" class="h-[300px]" />
      </template>
    </el-table>
    <div>
      <pagination
        :total="listCount"
        v-model:page="searchForm.pageNum"
        v-model:limit="searchForm.pageSize"
        @update:page="val => searchForm.pageNum = val"
        @update:limit="val => searchForm.pageSize = val"
        @pagination="getListData"
      />
    </div>
  </div>
</template>

<script setup>
import propsConfig from './props.js'
import { getTableData } from '@/api/table.js'
import pagination from '@/components/Pagination/index.vue'
import { defaultTo } from 'lodash'

const props = defineProps(propsConfig)
const emits = defineEmits(['selectionChange'])

const listData = ref([]) // 表格数据集合
const additionalData = ref([]) // 额外数据
const listCount = ref(0) // 总条数
const selectedData = ref(props.selectColumnType === 'CHECKBOX' ? [] : 0) // 选中列表集合
const tableRef = ref(null) // table对象
const expandsKey = ref([]) // 当前展开行
const loading = ref(false) // 表格loading加载
// const searchForm = ref({
//   pageSize: defaultTo(props.propsSearchForm.pageSize, 10),
//   pageNum: defaultTo(props.propsSearchForm.pageNum, 1)
// }) // 查询条件 - 页码条数
const searchForm = computed(() => {
  const { pageSize, pageNum, ...surplus } = props.propsSearchForm
  return {
    pageSize: defaultTo(pageSize, 10), // 默认10
    pageNum: defaultTo(pageNum, 1), // 默认1
    ...surplus
  }
}) // 表格搜索条件处理

// 查询表格
const getListData = async () => {
  loading.value = true
  tableRef.value?.clearSelection()
  emits('selectionChange', props.selectColumnType === 'CHECKBOX' ? [] : 0)

  // 重置表格集合数据和编辑集合数据
  listData.value = []
  expandsKey.value = [] // 扩展行关闭
  try {
    // 查询所有
    const res = await getTableData(props.reqRequest, searchForm.value)
    if (res.rows) {
      const { list, count } = props.handleData(res.rows.data || res.rows, res.total || 0)
      listCount.value = count
      listData.value = list
      additionalData.value = res.surplus // 设置额外数据
    }

    if (res.data) {
      const { list, count } = props.handleData(res.data.data || res.data, res.total || 0)
      listCount.value = count
      listData.value = list
      additionalData.value = res.surplus // 设置额外数据
    }
  } catch {
    listCount.value = 0
  } finally {
    loading.value = false
  }
}

// 选中方法
const handleSelectionChange = rows => {
  selectedData.value = props.selectColumnType === 'CHECKBOX' ? [] : 0 // 只有主键的集合
  let selected = props.selectColumnType === 'CHECKBOX' ? [] : 0 // 返还给父级组件的详情数据

  // 区分多选和单选
  if (props.selectColumnType === 'CHECKBOX') {
    if (typeof rows === 'number') {
      const data = listData.value?.find(row => {
        return row[props.selectKey] === rows
      })
      selectedData.value = rows
      selected.push(data)
    } else {
      if (rows) {
        selected = rows.map(row => {
          if (row) {
            selectedData.value.push(row[props.selectKey])
            return row
          }
        })
      }
    }
  } else {
    selected = rows
  }

  emits('selectionChange', selected)
}

// 回显定义的字段
const echoField = (options, value, label, data) => {
  if (data === undefined) {
    return ''
  }
  var actions = []
  Object.keys(options).some(key => {
    if (options[key][value] == '' + data) {
      actions.push(options[key][label])
      return true
    }
  })
  if (actions.length === 0) {
    actions.push(data)
  }
  return actions.join('')
  // 在数组中找到该对象
  // const temporary = data?.find(item => {
  //   return item[key] === value
  // })
  // return temporary ? temporary[labelKey] : ''
}

// 设置自定义数据
const setListData = data => {
  listData.value = data
  listCount.value = data.length
}

// 点击展开行的回调
const expandColumn = async (row, expandedRows) => {
  // 当扩展开启时候使用
  if (props.expendConfig.visible) {
    const flag = await props.expendConfig.expendFun(row) // 获取是否展开的标识请求
    // if (props.expendConfig.collapse) expandsKey.value = []

    const key = expandsKey.value.findIndex(item => {
      return item === row[props.selectKey]
    })
    if (flag) {
      if (key !== -1) {
        expandsKey.value.splice(key, 1)
      } else {
        if (props.expendConfig.collapse) {
          expandsKey.value = [row[props.selectKey]]
        } else {
          expandsKey.value.push(row[props.selectKey])
        }
      }
      // if (expandedRows.length) {
      //   // 展开
      //   expandsKey.value = [] // 先干掉之前展开的行
      //   if (row) expandsKey.value.push(row[props.selectKey]) // push新的行 (原理有点类似防抖)
      // } else {
      //   expandsKey.value = [] // 折叠 就清空expand-row-keys对应的数组
      // }
    } else {
      expandsKey.value.splice(key, 1)
    }
  }
}

// 禁止选中多选框集合方法
const disableIdsReturen = row => {
  return !(!row[props.selectKey] || props.disableIds.includes(row[props.selectKey]))
}
``
// 导出
const download = () => {}

onMounted(() => {
  if (props.initialize) getListData()
})

// 设置默认选中行
watch(() => props.defaultCheckList, newValue => {
  selectedData.value = newValue
  nextTick(() => {
    if (props.selectColumnType === 'CHECKBOX') {
      // 多选默认赋值
      newValue.forEach(row => {
        const data = listData.value.find(item => item[props.selectKey] === row)
        tableRef.value.toggleRowSelection(data, true)
      })
    }
  })
})

defineExpose({ getListData, setListData, expandColumn, listData, expandsKey })
</script>

<style lang="scss" scoped>
:deep(.el-table) {
  .cell.el-tooltip {
    display: flex;
    padding: 0;
  }
  .el-table__inner-wrapper::before {
    //background-color: transparent;
    display: none;
  }
  /*.el-table__cell {
    border-bottom: 1px solid #EDF2F7;
  }*/
  :deep(.el-table--default .el-table__cell) {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
  }
  :deep(.cell:has(.el-table__expand-icon)) {
    padding: 0;
  }
  .cell:has(.el-table__expand-icon) {
    display: flex;
    align-items: center;
  }
  :deep(.el-table__expand-icon) {
    color: var(--el-color-primary);
    .el-icon {
      font-size: 18px !important;
    }
  }

  .el-table__empty-block {
    height: 300px !important;
  }

  // 处理固定列纵向滚动条
  .el-table__header-wrapper tr td.el-table-fixed-column--left.is-last-column::before,
  .el-table__header-wrapper tr td.el-table-fixed-column--left.is-first-column::before,
  .el-table__header-wrapper tr td.el-table-fixed-column--right.is-last-column::before,
  .el-table__header-wrapper tr td.el-table-fixed-column--right.is-first-column::before,
  .el-table__header-wrapper tr th.el-table-fixed-column--left.is-last-column::before,
  .el-table__header-wrapper tr th.el-table-fixed-column--left.is-first-column::before,
  .el-table__header-wrapper tr th.el-table-fixed-column--right.is-last-column::before,
  .el-table__header-wrapper tr th.el-table-fixed-column--right.is-first-column::before,
  .el-table__body-wrapper tr td.el-table-fixed-column--left.is-last-column::before,
  .el-table__body-wrapper tr td.el-table-fixed-column--left.is-first-column::before,
  .el-table__body-wrapper tr td.el-table-fixed-column--right.is-last-column::before,
  .el-table__body-wrapper tr td.el-table-fixed-column--right.is-first-column::before,
  .el-table__body-wrapper tr th.el-table-fixed-column--left.is-last-column::before,
  .el-table__body-wrapper tr th.el-table-fixed-column--left.is-first-column::before,
  .el-table__body-wrapper tr th.el-table-fixed-column--right.is-last-column::before,
  .el-table__body-wrapper tr th.el-table-fixed-column--right.is-first-column::before,
  .el-table__footer-wrapper tr td.el-table-fixed-column--left.is-last-column::before,
  .el-table__footer-wrapper tr td.el-table-fixed-column--left.is-first-column::before,
  .el-table__footer-wrapper tr td.el-table-fixed-column--right.is-last-column::before,
  .el-table__footer-wrapper tr td.el-table-fixed-column--right.is-first-column::before,
  .el-table__footer-wrapper tr th.el-table-fixed-column--left.is-last-column::before,
  .el-table__footer-wrapper tr th.el-table-fixed-column--left.is-first-column::before,
  .el-table__footer-wrapper tr th.el-table-fixed-column--right.is-last-column::before,
  .el-table__footer-wrapper tr th.el-table-fixed-column--right.is-first-column::before {
    height: 100%;
  }
}

.textOverflow {
  display: flow;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
